(ns btree.core
  (:gen-class)
  (:use [btree.operations])
  (:use [btree.common])
)

(defn op-create
	[ptree page-size & args]
	(apply tree-create (concat [page-size] args))
)

(defn op-add
	[ptree page-size & args]
	(if (map? ptree)
		(apply tree-add (concat [ptree] args))
		"wykonaj najpierw 'create' by stworzyc drzewo"
	)
)

(defn op-remove
	[ptree page-size & args]
	(if (map? ptree)
		(apply tree-remove (concat [ptree] args))
		"wykonaj najpierw 'create' by stworzyc drzewo"
	)
)

(defn op-find
	[ptree page-size & args]
	(if (map? ptree)
		(nth (apply tree-find (concat [ptree] args)) 0)
		"wykonaj najpierw 'create' by stworzyc drzewo"
	)
)

(defn op-size
	[ptree page-size & args]
	(if (map? ptree)
		(apply tree-size (concat [ptree] args))
		"wykonaj najpierw 'create' by stworzyc drzewo"
	)
)

(defn main-loop
	[ptree psize]
	(print ">>")  
    (flush)
	(def line (read-line))
	(if (not (or (= line "exit") (= line "quit"))) (do
		(try (do
			(def command (load-string (str "'(btree.core/op-" line ")")))
			(def command (concat [(first command)] [ptree psize] (rest command)))
			(def result (eval command))
			(if (map? result) (do
					(println (tree-json result))
					(main-loop result psize)
				)
				(do
					(println result)
					(main-loop ptree psize)
				)
			)
		) (catch Exception e (do
			(println "Niepoprawna operacja. Dostepne operacje: create arg1 arg2 ..., add arg, remove arg, size, find arg, quit/exit")
			(main-loop ptree psize)
		)))
	))
)

(defn -main
	"an interactive command prompt."
	[& args]
	(println "quit lub exit aby wyjsc.")
	(flush)
	(main-loop nil 2)
)

